package com.stn.zjx.givingtreasure;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.format.Formatter;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;

import com.allenliu.badgeview.BadgeFactory;
import com.allenliu.badgeview.BadgeView;
import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.stn.zjx.givingtreasure.activity.web.GenericWebActivity;
import com.stn.zjx.givingtreasure.adapter.MainFragmentAdapter;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.constants.StnConstants;
import com.stn.zjx.givingtreasure.domain.UpdateVersionDomain;
import com.stn.zjx.givingtreasure.event.ExitEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.RefreshEvent;
import com.stn.zjx.givingtreasure.fragment.main.MainShopCartFragment;
import com.stn.zjx.givingtreasure.fragment.main.MainShopFragment;
import com.stn.zjx.givingtreasure.fragment.main.MainIndexFragment;
import com.stn.zjx.givingtreasure.fragment.main.MainMyFragment;
import com.stn.zjx.givingtreasure.fragment.main.MainActiveFragment;
import com.stn.zjx.givingtreasure.fragment.main.MainTypeFragment;
import com.stn.zjx.givingtreasure.glide.GlideImageGetter;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.CheckVersionNetImpl;
import com.stn.zjx.givingtreasure.net.impl.MsgNetImpl;
import com.stn.zjx.givingtreasure.service.AppUpdateService;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.StatusBarUtil;
import com.stn.zjx.givingtreasure.widget.NoScrollViewPager;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxAppTool;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.RxSPTool;

import com.zzhoujay.richtext.RichText;
import com.zzhoujay.richtext.callback.OnUrlClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends BaseActivity implements TabLayout.BaseOnTabSelectedListener {

    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.viewpager)
    NoScrollViewPager viewpager;
    //底部菜单文字内容，集合
    @BindArray(R.array.main_ar)
    String[] mainMenu;
    //底部菜单图片，集合
    int[] imgsMenu = new int[]{
            R.mipmap.main_index_press, R.mipmap.main_index_nopress,
            R.mipmap.main_buy_press, R.mipmap.main_buy_nopress,
            R.mipmap.main_show_press, R.mipmap.main_show_nopress,
            R.mipmap.main_shop_cart_press, R.mipmap.main_shop_cart_nopress,
            R.mipmap.main_my_press, R.mipmap.main_my_nopress
    };
    private MainIndexFragment index;
    private MainTypeFragment type;
    private MainShopFragment buy;
    private MainActiveFragment show;
    private MainFragmentAdapter mainAdapter;
    private MainMyFragment my;
    private BadgeView badgeView;
    public Dialog update_dialog;
    private TextView vs_title;
    private TextView vs_size;
    private TextView vs_info;
    private ButtonBgUi vs_ok;
    private TextView tv_ignore;
   private String update_url="";
    private MainShopCartFragment shopCart;

    @Subscribe(threadMode = ThreadMode.MAIN)
   public void ExitEvent(ExitEvent exitEvent){
          switch (exitEvent.flag){
              case ExitEvent.SWITCH_LANGUAGE_EXIT:
                  RxActivityTool.skipActivity(this, MainActivity.class);
                  finish();
                  break;
          }
   }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initComponent();

    }

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {
             if(!RxNetTool.isNetworkAvailable(this)){
//                                          Sneaker  sneaker=Sneaker.with(this)
//
//                                                    .autoHide(true)
//                                                    .setTitle(getString(R.string.network_no_check), R.color.white);
//                                            sneaker .sneak(R.color.black);
//                 sneaker.setOnSneakerDismissListener(new OnSneakerDismissListener() {
//                     @Override
//                     public void onDismiss() {
//                         showToast("dasasdad");
//                     }
//                 });
//                                          sneaker.sneakError();


             }
    }

    @Override
    public void initComponent() {
        StatusBarUtil.setImmersiveStatusBar(MainActivity.this,false);
        setupTabIcons();
        initUpdateDialaog();

    }
    public void initUpdateDialaog(){
        update_dialog=new Dialog(this);
        Objects.requireNonNull(update_dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(ActivityCompat.getColor(this,R.color.translucent)));
        update_dialog.setContentView(R.layout.dialog_update_version);
        update_dialog.setCanceledOnTouchOutside(false);
        View ll_top=update_dialog.findViewById(R.id.ll_top);
        vs_title=update_dialog.findViewById(R.id.tv_title);
        vs_size=update_dialog.findViewById(R.id.version_size);
        vs_info=update_dialog.findViewById(R.id.tv_update_info);
        vs_ok=update_dialog.findViewById(R.id.btn_ok);
        vs_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] perms = {Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                };
                //是否有以上权限
                if (EasyPermissions.hasPermissions(MainActivity.this, perms)) {
                    Intent start=new Intent(MainActivity.this,AppUpdateService.class);
                    start.putExtra("download_url",update_url);
                    startService(start);
                    update_dialog.dismiss();
                } else {
                    //发起请求权限
                    // Do not have permissions, request them now
                    EasyPermissions.requestPermissions(MainActivity.this, getString(R.string.request_perssion_desc),
                            100, perms);
                }


            }
        });
        tv_ignore=update_dialog.findViewById(R.id.tv_ignore);
        tv_ignore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RxSPTool.putBoolean(getApplicationContext(),StnConstants.isCloseCehckVersion,true);
                update_dialog.dismiss();
            }
        });
        update_dialog.findViewById(R.id.iv_close)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        update_dialog.dismiss();
                    }
                });

     String[]   perms= {Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_NETWORK_STATE
        };
        //是否有以上权限
        if (EasyPermissions.hasPermissions(MainActivity.this, perms)) {
            checkVersion();
        } else {
            //发起请求权限
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(MainActivity.this, getString(R.string.request_perssion_desc),
                    100, perms);
        }


    }

    //初始化底部选项文字以及图片
    public void setupTabIcons() {
        if (mainMenu == null || mainMenu.length == 0 || tablayout == null) {
            return;
        }
        int size = mainMenu.length;
      //  viewpager.setOffscreenPageLimit(mainMenu.length-1);
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(index = new MainIndexFragment());
        fragmentList.add(buy = new MainShopFragment());
        fragmentList.add(show = new MainActiveFragment());
        fragmentList.add(shopCart = new MainShopCartFragment());
        fragmentList.add(my = new MainMyFragment());
        viewpager.setAdapter(mainAdapter = new MainFragmentAdapter(this, getSupportFragmentManager(), fragmentList));
        viewpager.setNoScroll(true);
        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                       switch (i){
                           case 0:
                               StatusBarUtil.setImmersiveStatusBar(MainActivity.this,false);
                               break;
                           case 1:
                               StatusBarUtil.setImmersiveStatusBar(MainActivity.this,true);
                               break;
                           case 2:
                               StatusBarUtil.setImmersiveStatusBar(MainActivity.this,true);
                               break;
                           case 3:
                               StatusBarUtil.setImmersiveStatusBar(MainActivity.this,true);
                               break;
                           case 4:
                               StatusBarUtil.setImmersiveStatusBar(MainActivity.this,false);
                               break;
                       }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        for (int i = 0; i < size; i++) {
         TabLayout.Tab tab=tablayout.newTab().setCustomView(getTabView(i));
            tablayout.addTab(tab);
        }
      TabLayout.Tab tab=tablayout.getTabAt(tablayout.getTabCount()-1);
        badgeView= BadgeFactory.create(this)
                .setTextColor(getResources().getColor(R.color.white))
                .setWidthAndHeight(16,16)
                .setBadgeBackground(getResources().getColor(R.color.red))
                .setTextSize(8)
                .setBadgeGravity(Gravity.RIGHT|Gravity.TOP)
                .setBadgeCount("1")
                .setShape(BadgeView.SHAPE_CIRCLE)
                .bind(tab.getCustomView());
        badgeView.setVisibility(View.GONE);

        //监听被选中子菜单
        tablayout.addOnTabSelectedListener(this);


    }
    /**
     * 获取子菜单
     *
     * @param position 当前位置
     * @return 得到子菜单选项
     */
    //得到底部子菜单选项
    public View getTabView(int position) {
        View tabView = View.inflate(this, R.layout.item_main_tab, null);
        tabView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                TableLayout.LayoutParams.MATCH_PARENT));
        TextView txt_title = tabView.findViewById(R.id.txt_title);
        txt_title.setText(mainMenu[position]);
        ImageView img_title = tabView.findViewById(R.id.img_title);
        if (position == 0) {
            txt_title.setTextColor(getResources().getColor(R.color.colorAccent));
            img_title.setImageResource(imgsMenu[position * 2]);
        } else {
            txt_title.setTextColor(getResources().getColor(R.color.default_black));
            img_title.setImageResource(imgsMenu[position * 2 + 1]);
        }
        return tabView;
    }

    /**
     * 当被选中变化子菜单内容
     *
     * @param tab 子菜单组件
     */
    //选中时tab字体颜色和icon
    private void changeTabSelect(TabLayout.Tab tab) {
        //如果不等于空
        assert tab.getCustomView() != null;
        ImageView img_title = tab.getCustomView().findViewById(R.id.img_title);
        TextView txt_title = tab.getCustomView().findViewById(R.id.txt_title);
        int position = tab.getPosition();
        txt_title.setTextColor(getResources().getColor(R.color.colorAccent));
        img_title.setImageResource(imgsMenu[position * 2]);
        viewpager.setCurrentItem(tablayout.getSelectedTabPosition(), false);
//        AnimationSet animationSet = new AnimationSet(true);
//        ScaleAnimation scaleAnimation = new ScaleAnimation(1,1.2f,1,1.2f,
//                Animation.RELATIVE_TO_SELF,1.0f,Animation.RELATIVE_TO_SELF,1.0f);
//        //3秒完成动画
//        scaleAnimation.setDuration(100);
//        //将AlphaAnimation这个已经设置好的动画添加到 AnimationSet中
//        animationSet.addAnimation(scaleAnimation);
//        //启动动画
//        img_title .startAnimation(animationSet);
    }

    /**
     * 没有被选中变化子菜单内容
     *
     * @param tab 子菜单组件
     */
    //默认tab字体颜色和icon
    private void changeTabNormal(TabLayout.Tab tab) {
        assert tab.getCustomView() != null;
        ImageView img_title = tab.getCustomView().findViewById(R.id.img_title);
        TextView txt_title = tab.getCustomView().findViewById(R.id.txt_title);
        int position = tab.getPosition();
        txt_title.setTextColor(getResources().getColor(R.color.default_black));
        img_title.setImageResource(imgsMenu[position * 2 + 1]);

    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        changeTabSelect(tab);
        viewpager.setCurrentItem(tab.getPosition(), false);
    }

    //监听子菜单没被选中
    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        changeTabNormal(tab);
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    protected void onStart() {
        super.onStart();
        initData();
    }

    public void initData(){
        if (UserService.getInstance(this).getOnlineLoginUser() == null) {
              initDefault();
            return;
        }
        User userOnline = UserService.getInstance(this).getOnlineLoginUser();
        SharedPreferences sp =getSharedPreferences(StnConstants.MSG_COUNT_SHOW, Context.MODE_PRIVATE);
        if(sp.getBoolean(StnConstants.MSG_COUNT_SHOW,true)){
            MsgNetImpl
                    .query_get_no_read_all_msg(userOnline.getToken(), "query_get_no_read_all_msg",
                            new StringCallback() {
                                @Override
                                public void onSuccess(Response<String> response) {

                                    try {
                                        JSONObject result=new JSONObject(response.body());
                                        switch (result.getInt(BaseApi.KEY_STATUS)){
                                            case BaseApi.REQUEST_SUCCESS_CODE:
                                                int  msg_count=result.getInt("data");
                                                if(msg_count==0){
                                                    badgeView.setVisibility(View.GONE);
                                                }else{
                                                    if(msg_count>=99){
                                                        badgeView.setBadgeCount("99+");
                                                    }else{
                                                        badgeView.setBadgeCount(""+msg_count);
                                                    }
                                                    badgeView.setVisibility(View.VISIBLE);
                                                }
                                                break;
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onCacheSuccess(Response<String> response) {
                                    super.onCacheSuccess(response);
                                    try {
                                        JSONObject result=new JSONObject(response.body());
                                        switch (result.getInt(BaseApi.KEY_STATUS)){
                                            case BaseApi.REQUEST_SUCCESS_CODE:
                                                int  msg_count=result.getInt("data");
                                                if(msg_count==0){
                                                    badgeView.setVisibility(View.GONE);
                                                }else{
                                                    if(msg_count>=99){
                                                        badgeView.setBadgeCount("99+");
                                                    }else{
                                                        badgeView.setBadgeCount(""+msg_count);
                                                    }
                                                    badgeView.setVisibility(View.VISIBLE);
                                                }
                                                break;
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
        }else{

                badgeView.setVisibility(View.GONE);
        }



    }

    public void initDefault(){
        badgeView.setVisibility(View.GONE);
    }


    public void checkVersion(){


        if(RxSPTool.getBoolean(this, StnConstants.WALN_AUTO_UPDATE_VERSION)&&
                RxNetTool.isWifi(this)){

            CheckVersionNetImpl.get_version(0, "get_version",
                    new StringCallback() {
                        @SuppressLint("SetTextI18n")
                        @Override
                        public void onSuccess(Response<String> response) {
                            if(response.isSuccessful()&&!isFinishing()){
                                UpdateVersionDomain domain=new Gson().fromJson(response.body(),UpdateVersionDomain.class);
                                switch (domain.getStatus()){
                                    case BaseApi.REQUEST_SUCCESS_CODE:
                                        if(domain.getData()!=null){
                                            int local_code=RxAppTool.getAppVersionCode(getApplicationContext());
                                            if(local_code<domain.getData().getAppCode()){
                                                String[]   perms= {Manifest.permission.CAMERA,
                                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                                        Manifest.permission.ACCESS_FINE_LOCATION,
                                                        Manifest.permission.ACCESS_COARSE_LOCATION,
                                                        Manifest.permission.ACCESS_NETWORK_STATE
                                                };
                                                update_url=domain.getData().getAppUrl();
                                                //是否有以上权限
                                                if (EasyPermissions.hasPermissions(MainActivity.this, perms)) {
                                                    Intent start=new Intent(MainActivity.this,AppUpdateService.class);
                                                    start.putExtra("download_url",update_url);
                                                    startService(start);
                                                    update_dialog.dismiss();
                                                } else {
                                                    //发起请求权限
                                                    // Do not have permissions, request them now
                                                    EasyPermissions.requestPermissions(MainActivity.this, getString(R.string.request_perssion_desc),
                                                            100, perms);
                                                }
                                            }

                                        }
                                        break;
                                }
                            }

                        }
                    });
        }else{
            if(!RxSPTool.getBoolean(this,StnConstants.isCloseCehckVersion)){
                CheckVersionNetImpl.get_version(0, "get_version",
                        new StringCallback() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onSuccess(Response<String> response) {
                                if(response.isSuccessful()&&!isFinishing()){
                                    UpdateVersionDomain domain=new Gson().fromJson(response.body(),UpdateVersionDomain.class);
                                    switch (domain.getStatus()){
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            if(domain.getData()!=null){
                                                int local_code=RxAppTool.getAppVersionCode(getApplicationContext());
                                                if(local_code<domain.getData().getAppCode()){
                                                    String size=Formatter.formatFileSize(getApplicationContext(),domain.getData().getAppSize());
                                                    vs_title.setText(getString(R.string.upgradeto)+""+domain.getData().getAppVersion()+getString(R.string.version)+"?");
                                                    vs_size.setText(getString(R.string.new_version_size)+":"+ size);
                                                    // 加载富文本
                                                    RichText.from(domain.getData().getAppDescription())
                                                            .imageGetter(new GlideImageGetter(MainActivity.this))
                                                            .bind(MainActivity.this)
                                                            .urlClick(new OnUrlClickListener() {
                                                                @Override
                                                                public boolean urlClicked(String url) {
                                                                    Bundle bundle=new Bundle();
                                                                    bundle.putString("url",url);
                                                                    RxActivityTool.skipActivity(getApplicationContext(), GenericWebActivity.class,bundle);
                                                                    return true;
                                                                }
                                                            }).into(vs_info);
                                                    update_url=domain.getData().getAppUrl();
                                                    update_dialog.show();
                                                }

                                            }
                                            break;
                                    }
                                }

                            }
                        });
            }
        }




    }


    /**
     *
     * @param requestCode 请求权限代码
     * @param permissions  请求权限，字符串数组
     * @param grantResults 请求权限是否完成，状态数组
     */
    //请求权限返回结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

        String[] perms = {Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_NETWORK_STATE
        };
        if (EasyPermissions.hasPermissions(MainActivity.this, perms)) {
            RefreshEvent event=new RefreshEvent();
            event.flag=RefreshEvent.REFRESH;
            EventBus.getDefault().post(event);
            checkVersion();
        } else {

            //发起请求权限
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(MainActivity.this, getString(R.string.request_perssion_desc),
                    100, perms);
        }

    }




}
